// refresh-jwt.strategy.ts
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { Strategy, ExtractJwt } from 'passport-jwt';
import { Request } from 'express';
import { UserService } from 'src/user/user.service';
import { AppConfigService } from '../../config/config.service';

// 定义请求体的格式
interface AuthRequest extends Request {
  body: {
    refreshToken: string;
  };
}

@Injectable()
export class RefreshJwtStrategy extends PassportStrategy(
  Strategy,
  'jwt-refresh',
) {
  constructor(
    private readonly userService: UserService,
    private readonly configService: AppConfigService,
  ) {
    super({
      jwtFromRequest: ExtractJwt.fromExtractors([
        (req: AuthRequest) => {
          return req?.body?.refreshToken;
        },
      ]),
      secretOrKey: configService.jwtRefreshSecret,
      passReqToCallback: true,
    }); // 显式类型断言
  }

  async validate(req: AuthRequest, payload: { sub: string; username: string }) {
    // const refreshToken = req.headers['x-refresh-token'] as string;
    const refreshToken = req.body.refreshToken;
    console.log('refreshToken', refreshToken);
    console.log('payload', payload);
    const user = await this.userService.findById(Number(payload.sub));

    if (!user || user.refreshToken !== refreshToken) {
      throw new UnauthorizedException({
        message: 'Invalid token',
        code: 'INVALID_TOKEN',
      });
    }

    return user;
  }
}
